<template>
	<view class="checkout-page">
		<!-- 配送方式 -->
		<u-subsection :list="shippingTypes" :current="shippingType" @change='changeShippingType'></u-subsection>
		<!-- 地址选择 -->
		<view v-if='shippingType == 1' class="address-card" @click="chooseAddress">
			<view v-if="!selectedAddress" class="empty-address">
				<uni-icons type="location-filled" size="24"></uni-icons>
				<text>请选择收货地址</text>
			</view>
			<view v-else class="address-info">
				<view class="address-header">
					<text>{{selectedAddress.userName}}</text>
					<text>{{selectedAddress.telNumber}}</text>
				</view>
				<text class="address-detail">
					{{selectedAddress.provinceName}}{{selectedAddress.cityName}}{{selectedAddress.countyName}}{{selectedAddress.detailInfo}}
				</text>
			</view>
			<uni-icons type="arrowright" size="20"></uni-icons>
		</view>
		<view v-else class="address-card">
			<view >
				<view class="name" >自提门店:{{store.name}}</view>
				<view class="sub-title" >{{store.address}}</view>
				<view>
					<u--input
					    placeholder="请输入电话号码"
					    border="surround"
					    v-model="phone"
					  ></u--input>
				</view>
			</view>
		</view>
		<view style='padding:0px 20px;'>
			<u--textarea v-model="comment" placeholder="订单备注"></u--textarea>
		</view>
		<!-- 商品列表 -->
		<view class="goods-section">
			<view class="section-title">商品清单</view>
			<view class="goods-list">
				<view v-for="(item,index) in orderItems" :key="index" class="goods-item">
					<image :src="item.cover" mode="aspectFill" class="goods-image"></image>
					<view class="goods-info">
						<text class="goods-name">{{item.specification.product.__toString}}</text>
						<text class="goods-spec">{{item.specification.name}}</text>
						<view class="goods-bottom">
							<text class="goods-price">¥{{item.price}}</text>
							<text class="goods-quantity">x{{item.quantity}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 优惠券选择 -->
		<view v-if='availableCoupons && availableCoupons.length > 0' class="coupon-section" @click="show = true">
			<text>优惠券</text>
			<view class="coupon-right">
				<text v-if="!selectedCoupon">选择优惠券</text>
				<text v-else class="coupon-selected">{{selectedCoupon.name}}</text>
				<uni-icons type="arrowright" size="20"></uni-icons>
			</view>
		</view>

		<!--  -->
		<view v-if='point > 0' class="coupon-section">
			<text>积分抵扣<text style='color:#909399;font-size: 12px;'>可抵扣{{pointPaid}}元</text></text>
			<view class="coupon-right">
				<u-switch v-model="usePoint" activeColor='#19be6b' @change='getOrderCalculatePrice'></u-switch>
			</view>
		</view>

		<!-- 价格明细 -->
		<view class="price-section">
			<view class="price-row">
				<text>商品总价</text>
				<text>¥{{totalPrice.toFixed(2)}}</text>
			</view>
			<view v-if='discount > 0' class="price-row">
				<text>优惠</text>
				<text class='price-total'>-¥{{discount.toFixed(2)}}</text>
			</view>
			<view v-if='pointDiscount > 0' class="price-row">
				<text>积分抵扣</text>
				<text class='price-total'>-¥{{pointDiscount}}</text>
			</view>
			<view class="price-row total">
				<text>实付款</text>
				<text class="price-total">¥{{actualPrice.toFixed(2)}}</text>
			</view>
		</view>

		<!-- 支付按钮 -->
		<view class="footer">
			<view style='padding:10px'>
				<u-button text='立即支付' type='success' shape='circle' @click='createOrder'></u-button>
			</view>
		</view>

		<!-- 优惠券弹窗 -->
		<u-popup :show="show" @close="show = false">
			<view class="coupon-popup">
				<view class="popup-header">
					<text>选择优惠券</text>
					<uni-icons type="closeempty" size="24"></uni-icons>
				</view>
				<scroll-view scroll-y class="coupon-list">
					<view v-for="(item,index) in availableCoupons" :key="index" class="coupon-item"
						@click="selectCoupon(item)">
						<view class="coupon-left">
							<view class="coupon-value">¥{{item.value}}</view>
							<view class="coupon-condition">满{{item.condition}}元可用</view>
						</view>
						<view class="coupon-right">
							<view>{{item.name}}</view>
							<view style='color:#909399;font-size:14px;'>{{item.endTime}}到期</view>
						</view>
						<view v-if="selectedCoupon && selectedCoupon.id === item.id" class="coupon-selected-icon">
							<uni-icons type="checkmarkempty" color="#ff4d4f" size="24"></uni-icons>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import wechatPay from '@/utils/wechat-pay.js'
	export default {
		data() {
			return {
				selectedAddress: '',
				show: false,
				goodsList: [],
				availableCoupons: [],
				selectedCoupon: '',
				choosedCoupon: '',
				comment: '',
				totalPrice: 0,
				actualPrice: 0,
				discount: 0,
				orderItems: [],
				point: 0,
				usePoint: false,
				pointRate: 0,
				pointDiscount: 0,
				pointPaid: 0,
				shippingTypes: ['门店自提','物流配送'],
				shippingType: 1,
				store: '',
				phone: ''
			}
		},
		onShow() {
			this.store = uni.getStorageSync('store')
			this.goodsList = uni.getStorageSync('orderCarts')
			this.request.get(`api/options/POINT_EXCHANGE_RATE`).then((res) => {
				console.log('积分汇率',res.data)
				this.pointRate = res.data.value
				this.request.get(`api/balances`).then((res) => {
					console.log('balance', res.data)
					this.point = parseFloat(res.data.point)
					// 积分抵扣只能是整数
					this.pointPaid = parseInt(this.point * this.pointRate)
				})
			})
			this.request.get(`api/user-coupons`, {
				'@filter': `entity.getExpiredTime() >= datetime.get('now') && entity.getCoupon().getEnabled() == true && entity.getIsUsed() == false`,
				'@expands': "['entity.coupon']"
			}).then((res) => {
				console.log('coupon', res.data)
				let coupons = []
				for (let i of res.data) {
					let endTime = new Date(i.expiredTime)
					endTime = `${endTime.getFullYear()}.${endTime.getMonth() + 1}.${endTime.getDate()}`
					let value = i.coupon.__metadata.discount
					if (i.coupon.__metadata.type == 1) {
						value = `${parseInt(i.coupon.__metadata.discount * 10)}折`
					}
					let coupon = {
						id: i.id,
						name: i.coupon.__toString,
						value: value,
						endTime: endTime,
						condition: i.coupon.__metadata.threshold,
						type: i.coupon.__metadata.type,
						discount: i.coupon.__metadata.discount
					}
					coupons.push(coupon)
				}
				this.availableCoupons = coupons
				this.getOrderCalculatePrice()
			})
			
		},
		computed: {},
		methods: {
			chooseAddress() {
				uni.chooseAddress({
					success: (res) => {
						this.selectedAddress = res
						console.log('address', res)
					},
					fail: (err) => {
						console.log(err)
						uni.showToast({
							title: '获取地址失败',
							icon: 'none'
						})
					}
				})
			},
			changeShippingType(e){
				this.shippingType = e
			},
			createOrder() {
				if (this.selectedAddress == '' && this.shippingType == 1) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					})
					return
				}
				if(this.phone == '' && this.shippingType == 0){
					uni.showToast({
						title: '请输入电话号码',
						icon: 'none'
					})
					return
				}
				const tmplIds = [
					'uTZLnU0Ltow5L0KwpPfQ5t1YHpnduJKlMOAyg08ntw8'
				];
				uni.requestSubscribeMessage({
					tmplIds: tmplIds,
					success: res => {
						uni.showLoading()
						let items = []
						for (let i of this.goodsList) {
							items.push({
								specification: i.id,
								quantity: i.quantity
							})
						}
						let orderData = {
							store: this.store.id,
							items: items,
							comment: this.comment,
							phone: this.phone,
							shippingType: this.shippingType == 0 ? 'pickUp' : 'express'
						}
						if(this.shippingType != 0){
							orderData = {
								store: this.store.id,
								name: this.selectedAddress.userName,
								phone: this.selectedAddress.telNumber,
								address: `${this.selectedAddress.provinceName} ${this.selectedAddress.cityName} ${this.selectedAddress.countyName} ${this.selectedAddress.detailInfo}`,
								items: items,
								provinceName: this.selectedAddress.provinceName,
								cityName: this.selectedAddress.cityName,
								countyName: this.selectedAddress.countyName,
								postalCode: this.selectedAddress.postalCode,
								comment: this.comment,
								shippingType: this.shippingType == 0 ? 'pickUp' : 'express'
							}
						}
						
						if (this.selectedCoupon != '') {
							orderData['userCoupons'] = [this.selectedCoupon.id]
						}
						if(this.usePoint == true && this.pointPaid > 0){
							orderData['paidPoint'] = this.pointPaid / this.pointRate
						}
						this.request.post(`api/orders`, orderData).then((res) => {
							if(res.data.invoice){
								let invoiceId = res.data.invoice.id
								uni.hideLoading()
								wechatPay(invoiceId).then((res) => {
									uni.hideLoading()
									uni.showModal({
										title: '',
										content: '支付成功！',
										showCancel: false,
										success: () => {
											uni.redirectTo({
												url: '/pages/mine/orders'
											})
										}
									})
								}).catch((err) => {
									uni.hideLoading()
									uni.showModal({
										title: '',
										content: '支付失败，请重试',
										showCancel: false,
										success: () => {
											uni.redirectTo({
												url: '/pages/mine/orders'
											})
										}
									})
								})
							}else{
								uni.hideLoading()
								uni.showModal({
									title: '',
									content: '订单已支付',
									showCancel: false,
									success: () => {
										uni.redirectTo({
											url: '/pages/mine/orders'
										})
									}
								})
							}
							
						})
					}
				})

			},
			selectCoupon(coupon) {
				// console.log(coupon)
				if (this.totalPrice >= coupon.condition) {
					this.selectedCoupon = coupon
					// 计算价钱
					this.getOrderCalculatePrice()
					this.show = false
				} else {
					uni.showToast({
						title: `未满足${coupon.condition}元使用条件`,
						icon: 'none'
					})
				}
			},
			// 计算价钱
			getOrderCalculatePrice() {
				uni.showLoading()
				let items = []
				for (let i of this.goodsList) {
					items.push({
						specification: i.id,
						quantity: i.quantity
					})
				}
				let orderData = {
					items: items
				}
				if (this.selectedAddress) {
					orderData['address'] =
						`${this.selectedAddress.provinceName}${this.selectedAddress.cityName}${this.selectedAddress.detailInfo}`
				}
				if (this.selectedCoupon != '') {
					orderData['userCoupons'] = [this.selectedCoupon.id]
				}
				if(this.usePoint == true && this.point > 0){
					orderData['paidPoint'] = this.pointPaid
				}
				console.log('order', orderData)
				this.request.post(`api/orders/calculate-prices`, orderData).then((res) => {
					console.log('订单返回数据', res.data)
					// 查是否有用积分
					if(this.point > 0 && this.usePoint == true){
						this.pointDiscount = this.pointPaid
					}else{
						this.pointDiscount = 0
					}
					this.actualPrice = parseFloat(res.data.actualPrice) - this.pointDiscount
					this.totalPrice = parseFloat(res.data.totalPrice)
					this.discount = parseFloat(res.data.discount)
					this.orderItems = res.data.items
					uni.hideLoading()
				})
			},
		}
	}
</script>

<style>
	.checkout-page {
		padding-bottom: 120rpx;
	}

	.address-card {
		display: flex;
		align-items: center;
		padding: 30rpx;
		margin: 20rpx;
		background: #fff;
		border-radius: 16rpx;
	}

	.empty-address {
		display: flex;
		align-items: center;
		color: #999;
	}

	.address-info {
		flex: 1;
	}

	.address-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10rpx;
	}

	.address-detail {
		font-size: 26rpx;
		color: #666;
	}

	.goods-section {
		margin: 20rpx;
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
	}

	.section-title {
		font-weight: bold;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
	}

	.goods-item {
		display: flex;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.goods-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
	}

	.goods-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.goods-name {
		font-size: 28rpx;
		line-height: 1.4;
	}

	.goods-spec {
		font-size: 24rpx;
		color: #999;
	}

	.goods-bottom {
		display: flex;
		justify-content: space-between;
	}

	.goods-price {
		color: #f40;
		font-weight: bold;
	}

	.coupon-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		margin: 20rpx;
		background: #fff;
		border-radius: 16rpx;
	}

	.coupon-right {
		/* display: flex; */
		align-items: center;
	}

	.coupon-selected {
		color: #f40;
		margin-right: 10rpx;
	}

	.price-section {
		margin: 20rpx;
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
	}

	.price-row {
		display: flex;
		justify-content: space-between;
		padding: 15rpx 0;
	}

	.price-row.total {
		border-top: 1rpx solid #eee;
		margin-top: 10rpx;
		padding-top: 20rpx;
	}

	.price-total {
		color: #f40;
		font-size: 36rpx;
		font-weight: bold;
	}

	/* .footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
  width: 100%;
} */
	.pay-btn {
		background: #f40;
		color: #fff;
		border-radius: 50rpx;
		width: 250rpx;
	}

	.coupon-popup {
		background: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding: 30rpx;
		max-height: 70vh;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
		font-weight: bold;
	}

	.coupon-list {
		max-height: 60vh;
		padding-top: 20rpx;
	}

	.coupon-item {
		display: flex;
		padding: 25rpx;
		margin-bottom: 20rpx;
		background: #fff9f0;
		border-radius: 12rpx;
		position: relative;
	}

	.coupon-left {
		border-right: 1rpx dashed #ffd591;
		padding-right: 20rpx;
		margin-right: 20rpx;
	}

	.coupon-value {
		color: #f40;
		font-size: 36rpx;
		font-weight: bold;
	}

	.coupon-condition {
		font-size: 24rpx;
		color: #999;
	}

	.coupon-selected-icon {
		position: absolute;
		right: 20rpx;
		top: 50%;
		transform: translateY(-50%);
	}
	
	.name {
		font-weight: bold;
		margin-bottom: 5px;
	}
	
	.sub-title {
		font-size: 12px;
		color: #909399;
		margin-bottom:10px;
	}
</style>